import 'package:flutter_wanandroid_ohos/common/config/index.dart';
import 'package:flutter_wanandroid_ohos/generated/json/base/json_convert_content.dart';
import 'package:flutter_wanandroid_ohos/models/base_entity.dart';
import 'package:flutter_wanandroid_ohos/models/wx_chapter_entity.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold_ohos/getx_scaffold_ohos.dart';

import '../../models/article_entity.dart';
import '../../models/banner_entity.dart';
import '../../models/base_page_entity.dart';

class RecommendLogic extends GetxController with BaseListControllerMixin<ArticleEntity>{

  /// 轮播列表
  List<BannerEntity> bannerList = [];
  /// 公众号列表
  List<WxChapterEntity> wxChapterList = [];

  @override
  int get initPage => 0;

  @override
  int get pageSize => 20;

  @override
  void onReady() {
    super.onReady();
    onRefresh();
  }

  @override
  Future<List<ArticleEntity>> loadData(int page, int pageSize) async{
    if (page == initPage){
      getBannerList();
      getWxChapterList();
    }
    // 请求文章数据
    return getArticleList(page);
  }

  @override
  String get builderId => 'recommend';

  Future<void> getBannerList()async {
    var response = await HttpService.to.get(UrlConst.banner);
    if (response != null){
      var result = BaseEntity.fromJson(response.data);
      var list = JsonConvert.fromJsonAsT<List<BannerEntity>>(result.data);
      bannerList.clear();
      if(list != null && list.isNotEmpty) {
        bannerList.addAll(list);
      }
    }
  }

  Future<void> getWxChapterList()async{
    var response = await HttpService.to.get(UrlConst.wxChapterList);
    if (response != null){
      var result = BaseEntity.fromJson(response.data);
      var list = JsonConvert.fromJsonAsT<List<WxChapterEntity>>(result.data);
      wxChapterList.clear();
      if(list != null && list.isNotEmpty) {
        wxChapterList.addAll(list);
      }
    }
  }

  /// 请求文章列表
  Future<List<ArticleEntity>> getArticleList(int page) async {
    var response = await HttpService.to.get('${UrlConst.homeArticleList}/$page/json');
    if (response != null){
      var result = BaseEntity.fromJson(response.data);
      var pageBean = BasePageEntity.fromJson(result.data);
      var list = JsonConvert.fromJsonAsT<List<ArticleEntity>>(pageBean.datas);
      return list ?? [];
    }
    return [];
  }
}
